package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.commons.utils.Constants;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.vo.CountVO;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.ArrayOperators;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;


@DubboService
public class UserLikeApiImpl implements UserLikeApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Boolean saveOrUpdate(Long userId, Long likeUserId, boolean isLIke) {
        try {
            //1. 查询数据
            Query query = Query.query(Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId));
            UserLike userlike = mongoTemplate.findOne(query, UserLike.class);
            //2. 如果不存在,保存
            if (userlike == null){
                userlike = new UserLike();
                userlike.setUserId(userId);
                userlike.setLikeUserId(likeUserId);
                userlike.setCreated(System.currentTimeMillis());
                userlike.setUpdated(System.currentTimeMillis());
                userlike.setIsLike(isLIke);
                mongoTemplate.save(userlike);
            }else {
                //3. 存在，更新
                Update update = Update.update("isLike", isLIke)
                        .set("updated",System.currentTimeMillis());
                mongoTemplate.updateFirst(query,update,UserLike.class);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    //统计用户粉丝数量
    @Override
    public Integer counts(Long userId) {
        Query query = Query.query(Criteria.where("likeUserId").is(userId).and("isLike").is(true));
        long count = mongoTemplate.count(query, UserLike.class);
        return Integer.valueOf(String.valueOf(count));
    }

}
